<?php
require_once 'moriarty.inc.php';
class Rollback {
	
	var $sparqlservice;
	
	function __construct($sparqlservice){
		$this->sparqlservice = $sparqlservice;
	}


	/**
	 * resource_to_date
	 *
	 * @param $uri - uri of resource
	 * @param $date - date of resource state to revert back to
	 * @return HTTPResponse
	 * @author Keith
	 **/
	function resource_to_date($uri, $date){
		$query = 'DESCRIBE ?cs ?statement WHERE { ?cs <'.CS_SUBJECTOFCHANGE.'> <'.$uri.'> ; <'.CS_CREATEDDATE.'> ?date ; ?p ?statement . ?statement a <'.RDF_STATEMENT.'>  .  FILTER(?date <= "'.$date.'") } ';
		return $this->_run_query($query);		
	}


	/**
	 * to_changeset
	 *
	 * @param $cs_uri - uri of changeset to revert back to
	 * @return HTTPResponse
	 * @author Keith
	 **/	
	function to_changeset($cs_uri){
		$query = 'DESCRIBE <'.$cs_uri.'> ?statement WHERE { <'.$cs_uri.'> ?p ?statement . ?statement a <'.RDF_STATEMENT.'>   } ';
		return $this->_run_query($query);
		
	}
	
	function _run_query($query){
		$response = $this->sparqlservice->graph($query);
		if($response->is_success())
		{
			require_once MORIARTY_ARC_DIR.'/ARC2.php';
			$parser = ARC2::getRDFParser();
			$parser->parse(false, $response->body);
			$changeset = $this->revert_changes($parser->getSimpleIndex(0));
			$ser = ARC2::getRDFXMLSerializer();
	 		$response->body = $ser->getSerializedIndex($changeset);			
		}
		return $response;
	}
	
	function revert_changes($rdfphp){
		
		$cs_and_subjects = array(); //mapping of created cs IDs and subjects -one cs per subject uri
		$cs_no = 1;
		$revert = array(); // rdf/php array
		foreach($rdfphp as $uri => $properties){
			if(is_array($properties[RDF_TYPE]) AND $properties[RDF_TYPE][0]['value']==CS_CHANGESET){
				$s = $properties[CS_SUBJECTOFCHANGE][0]['value'];
				if(!isset($cs_and_subjects[$s])) $cs_and_subjects[$s] = '_:cs'.$cs_no++;

				$cs_ID  = $cs_and_subjects[$s];
				$revert[$cs_ID][RDF_TYPE][0] = array('value' => CS_CHANGESET, 'type' => 'uri');

				$revert[$cs_ID][CS_SUBJECTOFCHANGE][0] = array('value' => $s, 'type' => 'uri');
				$revert[$cs_ID][CS_CREATORNAME][0] = array('value' => 'Moriarty Rollback Class', 'type' => 'literal');
				$revert[$cs_ID][CS_CHANGEREASON][0] = array('value' => 'Rollbacked Change, generated by Moriarty Rollback Class', 'type' => 'literal');

				if(!empty($properties[CS_REMOVAL])) $revert[$cs_ID][CS_ADDITION] = $properties[CS_REMOVAL];
				if(!empty($properties[CS_ADDITION])) $revert[$cs_ID][CS_REMOVAL] = $properties[CS_ADDITION];	
				
			} else {
				$revert[$uri] = $properties;
			}
		}
		
		return $revert;
	}
	
}

?>